﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AuthoSYS.EF;

namespace AuthoSYS.Web.Controllers
{
    public class UserController : Controller
    {
        private AuthoDBEntities db = new AuthoDBEntities();

        //
        // GET: /User/

        public ActionResult Index(string appId)
        {
            var users = db.Users.Where(u => string.IsNullOrEmpty(appId) ? true : u.AppId == appId).ToList();

            ViewBag.AppId = appId;

            return View(users);
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(string id = null)
        {
            User user = db.Users.Single(u => u.Id == id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // GET: /User/Create

        public ActionResult Create(string appId)
        {

            User model = new User { Id = Guid.NewGuid().ToString(), AppId = appId ?? string.Empty };
            return View(model);
        }

        //
        // POST: /User/Create

        [HttpPost]
        public ActionResult Create(User user)
        {
            ModelState.Remove("Roles");

            if (ModelState.IsValid)
            {
                user.Id = Guid.NewGuid().ToString();
                user.ModifiedBy = string.Empty;
                user.ModifiedOn = DateTime.Now;
                user.CreatedBy = string.Empty;
                user.CreatedOn = DateTime.Now;
                user.AppUserId = string.Empty;
                user.SeletedRoles = Request["roles"];

                if (!string.IsNullOrEmpty(user.SeletedRoles))
                {
                    IEnumerable<UserRole> roles = user.SeletedRoles.Split(',').Select(r => new UserRole
                    {
                        Id = Guid.NewGuid().ToString(),
                        RoleId = r,
                        UserId = user.Id,
                        CreatedOn = DateTime.Now,
                        ModifiedOn = DateTime.Now
                    });

                    foreach (var r in roles)
                    {
                        user.Roles.Add(r);
                    }
                }

                db.Users.AddObject(user);
                db.SaveChanges();
                return RedirectToAction("Index", new { appId = user.AppId });
            }

            return View(user);
        }

        //
        // GET: /User/Edit/5

        public ActionResult Edit(string id = null)
        {
            User user = db.Users.Single(u => u.Id == id);
            user.SeletedRoles = string.Join(",", user.Roles.Select(r => r.RoleId).ToArray());
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        public ActionResult Edit(User user)
        {
            ModelState.Remove("Roles");

            if (ModelState.IsValid)
            {
                var userRoles = db.UserRoles.Where(ur => ur.UserId == user.Id);
                foreach (var ur in userRoles)
                {
                    db.UserRoles.DeleteObject(ur);
                }

                db.Users.Attach(user);

                user.SeletedRoles = Request["roles"];
                if (!string.IsNullOrEmpty(user.SeletedRoles))
                {
                    IEnumerable<UserRole> roles = user.SeletedRoles.Split(',').Select(r => new UserRole
                    {
                        Id = Guid.NewGuid().ToString(),
                        RoleId = r,
                        UserId = user.Id,
                        CreatedOn = DateTime.Now,
                        ModifiedOn = DateTime.Now
                    });

                    foreach (var r in roles)
                    {
                        user.Roles.Add(r);
                    }
                }


                user.ModifiedBy = string.Empty;
                user.ModifiedOn = DateTime.Now;

                db.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index", new { appId = user.AppId });
            }
            return View(user);
        }

        //
        // GET: /User/Delete/5

        public ActionResult Delete(string id = null)
        {
            User user = db.Users.Single(u => u.Id == id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /User/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            User user = db.Users.Single(u => u.Id == id);
            var userRoles = db.UserRoles.Where(ur => ur.UserId == user.Id);
            foreach (var ur in userRoles)
            {
                db.UserRoles.DeleteObject(ur);
            }

            db.Users.DeleteObject(user);
            db.SaveChanges();
            return RedirectToAction("Index", new { appId = user.AppId });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}